package com.example.jedis.client.transport;

import code.example.tool.LogFactory;
import redis.clients.jedis.exceptions.JedisException;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class RedisTransportImpl  implements RedisTransport{
    SocketChannel socketChannel = null;
    int cacheSize = 1024;

    public RedisTransportImpl(SocketChannel socketChannel){
        this.socketChannel = socketChannel;
    }

    public int  write(ByteBuffer byteBuffer){
        try {

            int size = socketChannel.write(byteBuffer);
            return size;
        }catch (Exception e){
            throw new JedisException(e);
        }
    }
    public ByteBuffer   read() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(cacheSize);
        read(byteBuffer);
        return byteBuffer;
    }
    public int  read(ByteBuffer byteBuffer) {
        try {
            int size =  socketChannel.read(byteBuffer);
            if(size <=0){
                throw new JedisException("read no data from channel");
            }else{
                return size;
            }
        }catch (Exception e){
            throw new JedisException(e);
        }
    }


}
